/**
 * 手机验证码登录
 *
 */
import { useEffect, useState } from "react";
import { View, Text, Image } from "@tarojs/components";
import {
  ApiUserLoginSendVerificationCode,
  ApiUserLoginUserLoginVerficationCode,
} from "@/api/auth";
import Taro, {
  navigateTo,
  switchTab,
  navigateBack,
  reLaunch,
} from "@tarojs/taro";
import pattern from "@/lib/pattern";
import { getSearchParams } from "@/lib/get-search-params";
import { getUserInfo } from "@/lib/auth";
import SmsCodeInput from "@/components/sms-code-input";
import { Form, Button, Input, SafeArea } from "@nutui/nutui-react-taro";
import { isWeChat } from "@/lib/platform";

function Login() {
  // const [checkedAgreement, setCheckedAgreement] = useState([]);
  const [phone, setPhone] = useState<string>("");
  const [sms, setSms] = useState<any>();
  const [smsCode, setSmsCode] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    /**
     * 如果登录过了返回首页
     */
    if (Taro.getStorageSync("auth")) {
      Taro.showToast({
        title: "您已登录过了",
        icon: "none",
        duration: 2000,
        success: () => {
          setTimeout(() => {
            reLaunch({
              url: "/pages/profile/index",
            });
          }, 2000);
        },
      });
    }
  }, []);

  /**
   * 表单提交
   * @param {}
   * @return
   */
  const handleSubmit = () => {
    // if (!checkedAgreement || checkedAgreement?.length < 1) {
    //   Taro.showToast({
    //     title: "请同意用户协议",
    //     icon: "none",
    //     duration: 2000,
    //   });
    //   return;
    // }
    if (!phone) {
      Taro.showToast({
        title: "请输入手机号",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    if (!pattern.mobile.test(phone)) {
      Taro.showToast({
        title: "手机号无效",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    if (!sms?.token) {
      Taro.showToast({
        title: "请先获取短信验证码",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    if (!smsCode) {
      Taro.showToast({
        title: "请输入验证码",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    const params = {
      sms: {
        token: sms?.token,
        code: smsCode,
      },
      loginFlag: "corp",
      phone,
      head: {
        clientId: "MBJvx]",
      },
    };
    setLoading(true);
    ApiUserLoginUserLoginVerficationCode(params)
      .then((res) => {
        const { token, exipreTime } = res.data;
        getUserInfo({
          token,
          exipreTime,
          callback: () => {
            const backurl = decodeURIComponent(
              decodeURIComponent(getSearchParams("backurl"))
            );
            const isSwitchTab = getSearchParams("isSwitchTab");
            if (backurl) {
              const _history = isSwitchTab ? switchTab : navigateTo;
              _history({
                url: backurl,
              });
            } else {
              navigateBack({
                delta: process.env.TARO_ENV === "h5" && !isWeChat() ? 1 : 2,
              });
            }
          },
        });
      })
      .finally(() => {
        setLoading(false);
      });
  };

  /**
   * 发送验证码
   * @param {}
   * @return
   */
  const onSendSmsRequest = async (ab) => {
    const params = {
      phone,
      head: {
        clientId: "MBJvx]",
      },
    };
    const { data }: any = await ApiUserLoginSendVerificationCode(params);
    setSms(data);
  };
  return (
    <View>
      <SafeArea position="top"></SafeArea>
      <View className="flex items-center justify-center my-[180rpx]">
        <Image
          src={require("@/assets/img/logo/icon-192x192.png")}
          className="w-[100rpx] h-[100rpx]"
        />
        <View className="ml-1 flex flex-col">
          <Text className="text-[36rpx] leading-none font-medium">
            <Text className="text-[#446ea3]">云上</Text>
            <Text className="text-[#bd6f3e]">之枫</Text>
          </Text>
          <Text className="text-[24rpx] text-[#aaa] leading-none mt-1">
            网络工作室
          </Text>
        </View>
      </View>
      <Form
        divider
        labelPosition="left"
        footer={
          <View className="mt-4 w-full">
            <Button
              size="large"
              formType="submit"
              block
              type="primary"
              loading={loading}
              disabled={loading}
              onClick={handleSubmit}
            >
              提交
            </Button>
          </View>
        }
      >
        <Form.Item required name="phone" className="!items-center h-[108rpx]">
          <Input
            className="nut-input-text"
            placeholder="请输入手机号"
            type="number"
            maxLength={11}
            onChange={setPhone}
          />
        </Form.Item>
        <Form.Item required name="smsCode" className="!items-center">
          <View className="flex gap-2">
            <Input
              className="nut-input-text"
              placeholder="请输入验证码"
              type="number"
              maxLength={5}
              onChange={setSmsCode}
            />
            <SmsCodeInput
              phone={phone}
              onRequest={onSendSmsRequest}
              disabled={phone.length < 11}
            />
          </View>
        </Form.Item>
      </Form>
    </View>
  );
}

export default Login;
